<template>
  <PrivacyPopup :auto-judge="privacyShow" @agree="agree"></PrivacyPopup>
  <PageLayout full:page-style="pageStyle">
    <template #header>
      <HeaderLayout show-back>
        <view>{{ $t('Pairing.ConfirmAppliance.Navigator.ConfirmAppliance.Title') }}</view>
      </HeaderLayout>
    </template>
    <view class="container">
      <view class="selectModalView">
        <view class="subTitle">{{
          applianceStatus == 0 ? $t('Pairing.ConfirmAppliance.FoundApplance.Title') : ''
        }}</view>
        <view class="title">
          <image
            src="@/static/icon_My_Afterservice_Hotline_BO.png"
            mode="aspectFill"
            class="apliance-icon"
            v-if="brand == 'BOSCH'"
          />
          <image
            src="@/static/icon_My_Afterservice_Hotline_SE.png"
            mode="aspectFill"
            class="apliance-icon"
            v-if="brand == 'SIEMENS'"
          />
          <text class="sery">{{ showApplianceVib }}</text>
        </view>

        <!-- <view class="samll-title" style="margin-top: 8rpx">{{ $t('晶御智能') }} {{ catelog_name }}</view> -->
        <view class="machineImage">
          <image class="itemImage" :src="imgUrl" :mode="applianceStatus == 1 ? 'aspectFill' : 'aspectFit'" />
        </view>
        <view class="machineTips"> {{ machineText }}</view>
      </view>
      <view class="bom" :class="{ 'sp-bom': applianceStatus == 1 }">
        <ActionButton @click="switchConnect">{{ confirmText }}</ActionButton>
      </view>
    </view>
    <Modal :visible="showSettingError" :title="$t('APP.Common.BoolthTips.Text')" @ok="openSettings" ok-text="去打开">
      <view class="model-tips system-modal">
        {{ $t('APP.Common.BoolthTips.TitleTips.Text') }}
      </view>
      <image :src="showSettingPic" style="width: 100%" mode="aspectFit"></image>
    </Modal>
    <Modal
      :visible="showLocationErrorPic ? true : false"
      :title="$t('APP.Pairing.Error.Android.WXMPLocation.Text')"
      @ok="showLocationErrorPic = ''"
      ok-text="知道了"
    >
      <image :src="showLocationErrorPic" style="width: 100%" mode="aspectFit"></image>
    </Modal>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import ActionButton from '@/common/actionButton/actionButton.vue'
import Modal from '@/common/modal.vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { getVibInfo, subscribeMsgUnreleasedVib, type ApplianceInfo } from '@/api/content'
import netconfig from '@/config/netconfig'
import { reportEventData } from '@/dataReport/dataReportUtil'
import keyUtils from '@/dataReport/keyUtils'
import store from '@/store'
import { useGlobalStore } from '@/store/global'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/store/auth'
import { actionDebounce, checkReason } from '@/utils/mpHelper'
import {
  checkLocationPermission,
  OS_SYSTEM_LOCATION_PERMISSION,
  APPLICATION_LOCATION_PERMISSION,
  WXMP_LOCATION_PERMISSION,
} from '@/utils/basicHelper'
import { httpRequestErrorHandle } from '@/httpRequest/helper/errorHelper'
import type { ErrorResponse } from '@/utils/request'
import { useEnvStore } from '@/store/env'
import loginHelper from '@/pluginHelper/login'
import PrivacyPopup from '@/pages/navigator/components/privacyPopup.vue'
import { PairingConfirmAgreePrivacy } from '@/constants/UniEventKeys'
const i18n = useI18n()
const envStore = useEnvStore()
const plantFrom = computed(() => envStore.systemInfo.platform)
const plugin = requirePlugin('pairing-plugin')
const authStore = useAuthStore()
const pageStyle = {
  backgroundColor: '#F4F4F4',
}
const applianceStatus = ref(0)
const applianceVib = ref('')
const machineText = ref('')
const confirmText = ref('')
const showSettingPic = ref('')
const showLocationErrorPic = ref<string | boolean>(false)
const showSettingError = ref(false)
let appliance: ApplianceInfo
let pairingSource: string
let hotSpotpwd: string
const imgUrl = ref('')
const brand = ref('')
let btnBlock: boolean = false
let global = useGlobalStore(store)
let isNeedUpdateToken: boolean = false
const privacyShow = ref(true)
console.error(getCurrentPages(), applianceVib.value, global.sceneNumber, global.sceneName, global.sucPage)
onLoad((options: any) => {
  console.info('onLoad', options)
  applianceVib.value = options.vib
  pairingSource = decodeURIComponent(options.pairingSource)
  hotSpotpwd = options.hotSpotpwd
  imgUrl.value = `${netconfig.PHOTO_IMAGE}${options.vib}/${options.vib}.png`
  getVibInformation()
})
onShow(() => {
  if (isNeedUpdateToken) {
    getVibInformation()
  }
})
function getVibInformation() {
  getVibInfo(applianceVib.value, true).then((res) => {
    if (res.code == 0) {
      appliance = res.data as ApplianceInfo
      brand.value = appliance.brand
      applianceStatus.value = appliance.launched
      if (netconfig.isTester && applianceStatus.value == 1) {
        applianceStatus.value = 0
      }
      // applianceStatus.value = 1
      switch (applianceStatus.value) {
        case 0:
          // 已配置已发布
          machineText.value = ''
          confirmText.value = i18n.t('Pairing.ConfirmAppliance.Pairing.Button.Text')
          return
        case 1:
          // 已配置未发布
          confirmText.value = i18n.t('Pairing.ConfirmAppliance.RemindLater.Button.Text')
          machineText.value = i18n.t('Pairing.ConfirmAppliance.AddingVib.Content.Text')
          imgUrl.value = i18n.t('Pairing.ConfirmAppliance.QRcodeFail.Image')
          return
        case 2:
          // 未配置
          uni.redirectTo({
            url: `/pages/pairing/scanErroreTip/scanErroreTip?result=''&errorCode=2`,
          })
          confirmText.value = ''
          machineText.value = ''
          return
      }
    } else if (res.code == 30002) {
      uni.redirectTo({
        url: `/pages/pairing/scanErroreTip/scanErroreTip?result=''&errorCode=2`,
      })
    } else {
      if (
        res.code == 910001 ||
        res.code == 10001 ||
        res.code == 20000 ||
        res.code == 20004 ||
        (res.code == 401 && res.key == 'invalid_token')
      ) {
        isNeedUpdateToken = true
      }
      httpRequestErrorHandle({ code: res.code, messageid: res.messageid, msg: res.msg } as ErrorResponse)
    }
  })
}
function openSettings() {
  showSettingError.value = false
  uni.openSetting({
    success: (res) => {},
  })
}
const switchConnect = actionDebounce({
  call: async () => {
    if (applianceStatus.value == 0) {
      clickConnect()
    } else if (applianceStatus.value == 1) {
      clickNotify()
    }
  },
})
async function clickConnect() {
  const checkSetting = await checkReason()
  if (!checkSetting) {
    return
  } else if (checkSetting != true && checkSetting.indexOf('bluetoothAuthorize')) {
    showSettingPic.value = checkSetting
    return (showSettingError.value = true)
  }
  // 位置判断
  try {
    await checkLocationPermission()
  } catch (error: any) {
    if (!error.Location) return
    if (error.Location === OS_SYSTEM_LOCATION_PERMISSION) {
      if (plantFrom.value === 'ios') {
        return (showLocationErrorPic.value = `${netconfig.ASSETSPRE}/Assets/icons/img_pop_Location_iOS2.png`) //蓝牙使用判断
      } else {
        return uni.showModal({
          title: i18n.t('LocationPermission.System.Dialog.Title.Text'),
          content: i18n.t('LocationPermission.System.Pairing.Dialog.Text'),
        })
      }
    } else if (error.Location === APPLICATION_LOCATION_PERMISSION) {
      if (plantFrom.value === 'ios') {
        return (showLocationErrorPic.value = `${netconfig.ASSETSPRE}/Assets/icons/img_pop_Location_iOS.png`) //蓝牙使用判断
      } else {
        return (showLocationErrorPic.value = `${netconfig.ASSETSPRE}/Assets/icons/img_pop_Location_Android.png`) //蓝牙使用判断
      }
    } else if (error.Location === WXMP_LOCATION_PERMISSION) {
      return uni.showModal({
        title: i18n.t('LocationPermission.WXMP_LOCATION_PERMISSION.title.text'),
        content: i18n.t('LocationPermission.WXMP_LOCATION_PERMISSION.text'),
        confirmText: i18n.t('APP.Common.GoToAuthorization.Text'),
        success: (res) => {
          if (res.confirm) {
            openSettings()
          } else if (res.cancel) {
            console.log('cancel...')
          }
        },
      })
    }
  }

  reportEventData('pair_jump', {
    appliance_vib: applianceVib.value,
    pairingSource: pairingSource,
  })
  btnBlock = true
  if (!authStore.accessToken || !authStore.accessOpenId) {
    loginHelper.noCiamIdLogin()
    return
  }
  plugin.initPluginHttpEnvironment(netconfig.PLUGIN_ENV, netconfig.isTester)
  plugin.initPluginData(authStore.accessToken, authStore.accessOpenId, authStore.key, authStore.iv)
  plugin.initPairingDeviceData(
    applianceVib.value,
    '',
    pairingSource,
    false,
    global.sceneNumber,
    global.sceneName,
    global.sucPage,
    getCurrentPages(),
    (obj: any) => {
      console.error(obj)
      wx.navigateTo({
        url: obj.url,
        success: (res) => {
          console.log('success', res)
        },
        fail: (error) => {
          console.error('fail', error)
        },
        complete: () => {
          btnBlock = false
        },
      })
    },
    hotSpotpwd,
    '',
    'HC3.0'
  )
}
async function clickNotify() {
  uni.requestSubscribeMessage({
    tmplIds: [netconfig.NeedPairingApplianceId],
    success(res) {
      subscribeMsgUnreleasedVib(applianceVib.value).then(
        (res) => {
          if (res.code == 0) {
            reportEventData(keyUtils.KEY_BUTTON_CLICK, {
              des: '订阅消息成功',
              page_name: '选择家电页面',
              button_name: '稍后提醒我',
            })
          } else {
            reportEventData(keyUtils.KEY_BUTTON_CLICK, {
              des: '订阅消息失败',
              page_name: '选择家电页面',
              button_name: '稍后提醒我',
            })
          }
        },
        (error) => {
          reportEventData(keyUtils.KEY_BUTTON_CLICK, {
            des: '订阅消息失败',
            page_name: '选择家电页面',
            button_name: '稍后提醒我',
          })
        }
      )
    },
    fail: (res) => {
      console.log('clickNotify ...requestSubscribeMessage ..fail', res)
    },
    complete: (res) => {
      console.log('clickNotify ...requestSubscribeMessage ..complete', res)
      uni.navigateBack()
    },
  })
}
const showApplianceVib = computed(() => {
  if (applianceVib.value === 'MR12010920') {
    return 'MR120'
  } else if (applianceVib.value === 'MR10010528') {
    return 'MR100'
  } else if (applianceVib.value === 'MR100iRF10720') {
    return 'MR100iRF'
  } else if (applianceVib.value === 'MR100iRF10720EMS') {
    return 'MR100iRFEMS'
  } else {
    return applianceVib.value
  }
})

function agree() {
  uni.$emit(PairingConfirmAgreePrivacy)
}
</script>

<style lang="less" scoped>
.apliance-icon {
  width: 172rpx;
  height: 48rpx;
  vertical-align: bottom;
  scale: 1.2;
}

.selectModalView {
  text-align: center;
}
.title {
  display: flex;
  justify-content: center;
  align-items: center;
}
.machineImage {
  margin: 64rpx 0 100rpx;
  box-sizing: border-box;
  padding: 0 20rpx;
  width: 100%;
}

.selectModalView {
  margin-bottom: 20rpx;
  .machineTips {
    color: #2c3846;
    text-align: center;
    font-size: 36rpx;
    font-weight: 500;
    margin-top: 48rpx;
    padding: 0 32rpx;
  }
}

.subTitle {
  margin: 72rpx 0 48rpx;
  height: 64rpx;
  font-weight: 500;
  font-size: 36rpx;
  line-height: 64rpx;
  color: var(--dark-color);
}

.samll-title {
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  font-size: 32rpx;
  line-height: 44rpx;
  color: var(--dark-color);
}

.itemImage {
  width: 374rpx;
  height: 418rpx;
}

.smallFridgeFreezerImg {
  width: 240rpx;
}

.bom {
  position: absolute;
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  bottom: 92rpx;
  padding: 0 32rpx;
  box-sizing: border-box;
  font-weight: 600;
  font-size: 32rpx;
  color: #ffffff;
}
.sp-bom {
  bottom: 17%;
}
.sery {
  margin-left: 16rpx;
  font-weight: 500;
  font-size: 32rpx;
  line-height: 44rpx;
  color: var(--dark-color);
}
</style>
